import json
import os

from rest_framework.exceptions import ValidationError


class Utils:
    @classmethod
    def validate(cls, validate_data: dict, validate_schema: dict):
        for param_name, type_name in validate_schema.items():
            # 要求数据拥有但格式不正确
            if param_name in validate_data and not isinstance(validate_data[param_name], type_name):
                raise ValidationError(f"请传递正确的数据格式{param_name}:{type_name}")

    @classmethod
    def filter_data(cls, data: dict):
        # 准备HR3格式模板，用来比对数据
        template = {
            'config': {
                'name': str,
                'base_url': str,
                'variables': dict,
                'parameters': dict,
                'verify': bool,
                'export': list
            },
            'teststeps': [{
                'name': str,
                'variables': list,
                'extract': dict,
                'validate': list,
                'setup_hooks': list,
                'teardown_hooks': list,
                'request': {
                    'method': str,
                    'url': str,
                    'params': list,
                    'headers': dict,
                    'cookies': dict,
                    'data': dict,
                    'json': dict
                },
            }]
        }
        return cls.merge_dict(template=template, datas=data)

    @classmethod
    def merge_dict(cls, template: dict, datas: dict):
        for data_key in list(datas.keys()):
            if data_key not in template:
                datas.pop(data_key)
            elif not datas[data_key]:
                if data_key != 'verify':
                    datas.pop(data_key)
                else:
                    if datas[data_key] is not None and isinstance(datas[data_key], template[data_key]):
                        pass
                    else:
                        datas.pop(data_key)
            else:
                if isinstance(datas[data_key], dict) and isinstance(template[data_key], dict):
                    cls.merge_dict(template[data_key], datas[data_key])
                elif isinstance(datas[data_key], list) and isinstance(template[data_key], list):
                    for data_list in datas[data_key]:
                        cls.merge_dict(template[data_key][0], data_list)
                elif not isinstance(datas[data_key], template[data_key]):
                    datas.pop(data_key)
        return datas

    @classmethod
    def setup_case_dir(cls, case_path):
        cls.empty_dir_files(case_path, 'json', 'py')

    """
    os.walk(path)
    /tmp/demo
    ├── a.txt
    ├── b.json
    └── subdir
        ├── c.py
        └── nested
            └── d.md

    for root, dirs, files in os.walk('/tmp/demo'):
        print("当前目录:", root)
        print("子目录:", dirs)
        print("文件:", files)
        print("-" * 20)
    当前目录: /tmp/demo
    子目录: ['subdir']
    文件: ['a.txt', 'b.json']
    --------------------
    当前目录: /tmp/demo/subdir
    子目录: ['nested']
    文件: ['c.py']
    --------------------
    当前目录: /tmp/demo/subdir/nested
    子目录: []
    文件: ['d.md']
    --------------------
    """
    @classmethod
    def empty_dir_files(cls, path, *suffix):
        print(os.path.abspath(path))
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(suffix):
                    os.remove(os.path.join(root, file))
    '''
    os.listdir(path)列出指定目录下的文件和文件夹名称
    '''
    @classmethod
    def collect_log(cls, path):
        collect_list = []
        for file in os.listdir(path):
            with open(f'{path}/{file}') as f:
                collect_list.append(f.read())
        return '\n'.join(collect_list)
